package com.example.demo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import jakarta.websocket.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@ClientEndpoint
public class MyClientEndpoint {
    private Session session;
    private CountDownLatch latch = new CountDownLatch(1);
    private String lastMessage;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("✅ 连接已建立，连接到: " + session.getRequestURI());
        latch.countDown(); // 通知主线程连接成功
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("📨 收到消息: " + message);
        this.lastMessage = message;
        // 这里可以处理收到的消息，比如解析JSON等
        try {
            int i = Integer.parseInt(message);
            System.out.println(cur + "onMessage：" + i);
            if (i < 7200) {
                config.setCurSj(cur);
                save();
            }
        } catch (Exception e) {
            END = true;
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("❌ 连接关闭: " + closeReason.getReasonPhrase());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("💥 发生错误:");
        throwable.printStackTrace();
    }

    // 发送消息的方法
    public void sendMessage(String message) throws IOException {
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
            System.out.println("📤 已发送: " + message);
        } else {
            System.err.println("无法发送消息，会话未打开");
        }
    }

    // 等待连接建立
    public boolean awaitConnection(long timeout, TimeUnit unit) throws InterruptedException {
        return latch.await(timeout, unit);
    }

    // 获取最后一次收到的消息（用于测试或简单交互）
    public String getLastMessage() {
        return lastMessage;
    }

    // 关闭连接
    public void close() throws IOException {
        if (session != null) {
            session.close();
        }
    }

    private static boolean END = false;
    private static final String CONFIG_PATH = "D:\\develop\\java\\sydata\\demo\\demo\\src\\main\\resources\\config.json";
    private static Config config;
    private static int JG = 6;
    private static int cur = 0;

    private static void load() {
        config = JSON.parseObject(FileUtil.readString(CONFIG_PATH, CharsetUtil.UTF_8), Config.class);
        cur = config.getCurSj();
    }

    private static void save() {
        FileUtil.writeString(JSON.toJSONString(config, JSONWriter.Feature.PrettyFormat), CONFIG_PATH, CharsetUtil.UTF_8);
    }

    public static void main(String[] args) {
        load();
        loadUserlog();
        // 要连接的 WebSocket 服务地址 (以 wss://echo.websocket.org 为例，这是一个公共测试服务)
        String serverUrl = "wss://sdckwss.5zk.com.cn/sdck_jjsp?session_id=" + config.getPhpsessid();
        MyClientEndpoint clientEndpoint = new MyClientEndpoint();
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            System.out.println("🔄 正在连接到: " + serverUrl);
            // 连接服务器
            container.connectToServer(clientEndpoint, new URI(serverUrl));
            // 等待连接建立（最多等5秒）
            if (clientEndpoint.awaitConnection(5, TimeUnit.SECONDS)) {
                System.out.println("✅ 成功连接到服务器！");
                while (!END) {
                    Thread.sleep(JG * 1000L);
                    cur = cur + JG;
                    cur = Math.min(config.getMaxSj(), cur);
                    clientEndpoint.sendMessage("Update1: jjwikiid=" + config.getCurJjwikiid() + "&TypeId=" + config.getTypeId() + "&cur_jindu=" + cur + "&userlog_id=" + config.getUserLogId());
                    if (cur >= config.getMaxSj()) {
                        List<String> list = config.getList();
                        int index = list.indexOf(config.getCurJjwikiid());
                        if (index != list.size() - 1) {
                            config.setCurJjwikiid(list.get(index + 1));
                            loadUserlog();
                        } else {
                            END = true;
                        }
                        cur = 0;
                    }
                }

//                Thread.sleep(JG * 1000L);
//                // 关闭连接
//                clientEndpoint.close();

            } else {
                System.err.println("连接超时");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loadUserlog() {
        String url = "https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm=" + config.getKcdm() + "&jjwikiid=" + config.getCurJjwikiid();
        System.out.println(url);
        HttpRequest get = HttpUtil.createGet(url);
        get.cookie("PHPSESSID=" + config.getPhpsessid());
        Document document = Jsoup.parse(get.execute().body());
        config.setUserLogId(document.getElementById("userlog_id").val());
        System.out.println("获取到userlog_id：" + config.getUserLogId());

        Elements elements = document.select(" .block-content ul li ");
        List<String> list = new ArrayList<>();
        for (Element element : elements) {
            String href = element.selectFirst("a").attr("href");
            if (StrUtil.isNotBlank(href)) {
                if (href.endsWith(config.getCurJjwikiid())) {
                    String div = element.select("div").get(1).text();
                    String[] timeArr = StrUtil.subBetween(div, "/", ")").split(":");
                    int total = Integer.parseInt(timeArr[0]) * 3600 + Integer.parseInt(timeArr[1]) * 60 + Integer.parseInt(timeArr[2]);
                    config.setMaxSj(total);
                    System.out.println("获取到视频时长：" + config.getMaxSj());
                }
                list.add(StrUtil.subAfter(href, "=", true));
            }
        }
        save();
    }
}
